using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DesktopHelper.Data;
using DesktopHelper.Models;
using DesktopHelper.Services;
using DesktopHelper.ViewModels;

namespace DesktopHelper
{
    public partial class MainWindow : Window
    {
        private readonly ILogger<MainWindow> _logger;
        private readonly DatabaseService _databaseService;
        private readonly PinnedImageService _pinnedImageService;
        private readonly MainViewModel _viewModel;

        public MainWindow()
        {
            InitializeComponent();
            
            // 获取服务实例（简单的方式）
            try
            {
                var app = (App)Application.Current;
                var serviceProvider = app.Host?.Services;
                
                if (serviceProvider != null)
                {
                    _logger = serviceProvider.GetRequiredService<ILogger<MainWindow>>();
                    _databaseService = serviceProvider.GetRequiredService<DatabaseService>();
                    _pinnedImageService = serviceProvider.GetRequiredService<PinnedImageService>();
                    _viewModel = serviceProvider.GetRequiredService<MainViewModel>();
                    
                    DataContext = _viewModel;
                    Loaded += MainWindow_Loaded;
                }
                else
                {
                    throw new InvalidOperationException("服务提供程序未初始化");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"初始化失败：{ex.Message}", "错误", 
                           MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
        }
        
        // 支持依赖注入的构造函数
        public MainWindow(ILogger<MainWindow> logger, DatabaseService databaseService, 
                         PinnedImageService pinnedImageService, MainViewModel viewModel)
        {
            InitializeComponent();
            
            _logger = logger;
            _databaseService = databaseService;
            _pinnedImageService = pinnedImageService;
            _viewModel = viewModel;
            
            DataContext = _viewModel;
            Loaded += MainWindow_Loaded;
        }

        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                await _viewModel.LoadDataAsync();
                StatusTextBlock.Text = "数据加载完成";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载数据失败");
                StatusTextBlock.Text = "数据加载失败";
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void RefreshButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StatusTextBlock.Text = "正在刷新...";
                await _viewModel.LoadDataAsync();
                StatusTextBlock.Text = "刷新完成";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新数据失败");
                StatusTextBlock.Text = "刷新失败";
                MessageBox.Show($"刷新失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void ClearHistoryButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = MessageBox.Show("确定要清空所有历史记录吗？此操作不可撤销。", "确认清空", 
                                            MessageBoxButton.YesNo, MessageBoxImage.Question);
                
                if (result == MessageBoxResult.Yes)
                {
                    StatusTextBlock.Text = "正在清空历史记录...";
                    await _viewModel.ClearAllHistoryAsync();
                    StatusTextBlock.Text = "历史记录已清空";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清空历史记录失败");
                StatusTextBlock.Text = "清空失败";
                MessageBox.Show($"清空失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void DeleteSelectedButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var activeTab = MainTabControl.SelectedItem as TabItem;
                if (activeTab == null) return;

                ListBox? activeListBox = activeTab.Name switch
                {
                    "TextTab" => TextListBox,
                    "ImageTab" => ImageListBox,
                    "FileTab" => FileListBox,
                    _ => null
                };

                if (activeListBox?.SelectedItems.Count > 0)
                {
                    var result = MessageBox.Show($"确定要删除选中的 {activeListBox.SelectedItems.Count} 项吗？", 
                                                "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    
                    if (result == MessageBoxResult.Yes)
                    {
                        StatusTextBlock.Text = "正在删除选中项...";
                        var selectedItems = activeListBox.SelectedItems.Cast<ClipboardItem>().ToList();
                        await _viewModel.DeleteItemsAsync(selectedItems);
                        StatusTextBlock.Text = $"已删除 {selectedItems.Count} 项";
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除选中项失败");
                StatusTextBlock.Text = "删除失败";
                MessageBox.Show($"删除失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                _viewModel.FilterItems(SearchTextBox.Text);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "搜索失败");
            }
        }

        private void ListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (sender is ListBox listBox && listBox.SelectedItem is ClipboardItem item)
                {
                    CopyItemToClipboard(item);
                    StatusTextBlock.Text = "已复制到剪贴板";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "双击复制失败");
                StatusTextBlock.Text = "复制失败";
            }
        }

        private void CopyButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is Button button && button.Tag is ClipboardItem item)
                {
                    CopyItemToClipboard(item);
                    StatusTextBlock.Text = "已复制到剪贴板";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "复制失败");
                StatusTextBlock.Text = "复制失败";
            }
        }

        private void CopyImageButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is Button button && button.Tag is ClipboardItem item && item.ImageData != null)
                {
                    using var stream = new MemoryStream(item.ImageData);
                    var bitmap = new System.Windows.Media.Imaging.BitmapImage();
                    bitmap.BeginInit();
                    bitmap.StreamSource = stream;
                    bitmap.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                    bitmap.Freeze();

                    Clipboard.SetImage(bitmap);
                    StatusTextBlock.Text = "图片已复制到剪贴板";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "复制图片失败");
                StatusTextBlock.Text = "复制图片失败";
            }
        }

        private async void PinImageButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is Button button && button.Tag is ClipboardItem item && item.ImageData != null)
                {
                    // 临时保存图片文件
                    var tempDir = Path.Combine(Path.GetTempPath(), "DesktopHelper");
                    Directory.CreateDirectory(tempDir);
                    var tempFile = Path.Combine(tempDir, $"temp_{DateTime.Now:yyyyMMddHHmmss}.png");
                    
                    await File.WriteAllBytesAsync(tempFile, item.ImageData);
                    
                    // 钉到桌面
                    await _pinnedImageService.PinImageToDesktop(tempFile);
                    StatusTextBlock.Text = "图片已钉到桌面";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "钉图失败");
                StatusTextBlock.Text = "钉图失败";
            }
        }

        private async void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (sender is Button button && button.Tag is ClipboardItem item)
                {
                    var result = MessageBox.Show("确定要删除此项吗？", "确认删除", 
                                                MessageBoxButton.YesNo, MessageBoxImage.Question);
                    
                    if (result == MessageBoxResult.Yes)
                    {
                        await _viewModel.DeleteItemAsync(item);
                        StatusTextBlock.Text = "项目已删除";
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除项目失败");
                StatusTextBlock.Text = "删除失败";
            }
        }

        private void CopyItemToClipboard(ClipboardItem item)
        {
            switch (item.Type)
            {
                case ClipboardDataType.Text:
                    if (!string.IsNullOrEmpty(item.Content))
                    {
                        Clipboard.SetText(item.Content);
                    }
                    break;

                case ClipboardDataType.Image:
                    if (item.ImageData != null)
                    {
                        using var stream = new MemoryStream(item.ImageData);
                        var bitmap = new System.Windows.Media.Imaging.BitmapImage();
                        bitmap.BeginInit();
                        bitmap.StreamSource = stream;
                        bitmap.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.OnLoad;
                        bitmap.EndInit();
                        bitmap.Freeze();

                        Clipboard.SetImage(bitmap);
                    }
                    break;

                case ClipboardDataType.File:
                    if (!string.IsNullOrEmpty(item.Content))
                    {
                        var files = item.Content.Split(';');
                        var stringCollection = new System.Collections.Specialized.StringCollection();
                        stringCollection.AddRange(files);
                        Clipboard.SetFileDropList(stringCollection);
                    }
                    break;
            }
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);

            // ESC 键隐藏窗口
            if (e.Key == Key.Escape)
            {
                Hide();
            }
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            // 隐藏窗口而不是关闭程序
            e.Cancel = true;
            Hide();
        }
    }
}